<template>
  <div class="app-container business-page">
    <div class="search-from">
      <el-form
        v-show="showSearch"
        id="searchFrom"
        :inline="true"
        :model="searchFrom"
        class="demo-form-inline"
      >
        <el-form-item>
          <el-input
            v-model.trim="searchFrom.keyword"
            clearable
            placeholder="请输入客户名称"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchFrom.status"
            clearable
            placeholder="商机阶段"
          >
            <el-option
              v-for="item in business_stage"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchFrom.resource"
            clearable
            placeholder="商机来源"
          >
            <el-option
              v-for="item in business_source"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="searchFrom.companyId"
            :data="companyOption"
            :disabled="useUserStore().userInfo.orgId != 484"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            class="w-full"
            default-expand-all
            placeholder="请选择所属公司"
            @change="getDeptTree()"
          />
        </el-form-item>
        <el-form-item>
          <el-tree-select
            v-model="searchFrom.deptId"
            :data="deptIdOption"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            class="w-full"
            placeholder="请选择所属部门"
          />
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchFrom.lastFollowTime"
            end-placeholder="最后跟进结束时间"
            range-separator="-"
            start-placeholder="最后跟进开始时间"
            style="width: 100%"
            type="daterange"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-select
            v-model="searchFrom.projectType"
            clearable
            placeholder="项目类型"
          >
            <el-option
              v-for="item in project_type"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="Search" type="primary" @click="handleQuery"
            >查询</el-button
          >
          <el-button icon="Refresh" type="default" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button icon="Plus" type="primary" @click="addItem"
            >添加</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            :disabled="multiple"
            icon="Switch"
            plain
            type="primary"
            @click="toBusiness"
            >转移商机</el-button
          >
        </el-col>

        <!-- <el-button
              @click="addCollaboration"
              icon="Connection"
              plain
              type="primary"
              >添加协作</el-button
            > -->
        <el-col :span="1.5">
          <el-button
            :disabled="single"
            icon="Edit"
            plain
            type="primary"
            @click="editItem"
            >编辑商机</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            :disabled="single"
            icon="Delete"
            plain
            type="primary"
            @click="delItem"
            >删除商机</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Upload"
            plain
            type="primary"
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入商机'
                uploadDiaType = 'business'
              }
            "
            >导入商机</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Upload"
            plain
            type="primary"
            @click="
              () => {
                uploadDia.open = true
                uploadDia.title = '导入跟进'
                uploadDiaType = 'followUp'
              }
            "
            >导入跟进</el-button
          >
        </el-col>
        <el-col :span="1.5">
          <el-button
            v-hasPermi="['salesManage:business:transfer']"
            icon="Download"
            plain
            type="primary"
            @click="exportFn"
            >导出</el-button
          >
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList">
          <el-tooltip
            :content="'自定义列表'"
            class="item"
            effect="dark"
            placement="top"
          >
            <el-button circle icon="Menu" @click="handleTable()" />
          </el-tooltip>
        </right-toolbar>
      </el-row>
    </div>
    <el-table
      v-loading="loading"
      :data="tableData"
      border
      stripe
      @selection-change="handleSelectionChange"
      @row-dblclick="handleClickProject"
    >
      <el-table-column type="selection" width="45" />
      <!-- <el-table-column prop="titleName" label="商机标题" width="200">
        <template #default="scope">
          <div style="color: #1890ff">
            {{ scope.row.titleName ? scope.row.titleName : '--' }}
          </div>
        </template>
      </el-table-column> -->
      <!--        ....-->
      <el-table-column
        v-for="(item, index) in tableCol.filter(item => item.show)"
        :key="index"
        v-bind="item"
      >
        <template #default="scope">
          <div v-if="item.tooltip">
            <el-tooltip
              :content="item.tooltip(scope.row)"
              :disabled="!scope.row.invoiceMsg"
              effect="dark"
              placement="top"
            >
              {{ item.tooltipVal(scope.row) }}
            </el-tooltip>
          </div>
          <div v-if="scope.column.label == '商机状态'">
            <span>{{
              business_stage.find(item1 => item1.value == scope.row.status)
                ? business_stage.find(item2 => item2.value == scope.row.status)
                    .label
                : '--'
            }}</span>
          </div>
          <div v-if="scope.column.label == '项目类型'">
            <span>{{
              project_type.find(item1 => item1.value == scope.row.projectType)
                ? project_type.find(
                    item2 => item2.value == scope.row.projectType
                  ).label
                : '--'
            }}</span>
          </div>
          <div v-if="scope.column.label == '商机来源'">
            <span>{{
              business_source.find(item1 => item1.value == scope.row.resource)
                ? business_source.find(
                    item2 => item2.value == scope.row.resource
                  ).label
                : '--'
            }}</span>
          </div>
          <div v-if="scope.column.label == '客户类型'">
            <span>{{
              business_customer_type.find(
                item1 => item1.value == scope.row.customerGenre
              )
                ? business_customer_type.find(
                    item2 => item2.value == scope.row.customerGenre
                  ).label
                : '--'
            }}</span>
          </div>
          <div v-if="scope.column.label == '客户行业'">
            <span>{{
              industry_category.find(
                item1 => item1.value == scope.row.customerIndustry
              )
                ? industry_category.find(
                    item2 => item2.value == scope.row.customerIndustry
                  ).label
                : '--'
            }}</span>
          </div>
          <div v-if="scope.column.label == '状态'">
            <span
              v-if="scope.row.approvalStatus"
              class="text-12px text-#999999"
              >{{ scope.row.approvalStatus }}</span
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="280">
        <template #default="scoped">
          <el-button
            icon="EditPen"
            plain
            size="small"
            type="primary"
            @click="toOrder(scoped.row)"
          >
            下单</el-button
          >
          <el-button
            icon="CircleCheck"
            plain
            size="small"
            type="success"
            @click="handleContinue(scoped.row)"
          >
            跟进</el-button
          >
          <el-button
            icon="CircleCheck"
            plain
            size="small"
            type="warning"
            @click="
              () => {
                router.push({
                  path: '/sales/contract/newContract',
                  query: {
                    t: 'business',
                    id: scoped.row.id,
                    c: scoped.row.customerName,
                    cI: scoped.row.customerId,
                    n: scoped.row.titleName
                  }
                })
              }
            "
            >添加合同</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      v-model:limit="searchFrom.pageSize"
      v-model:page="searchFrom.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 跟进 -->
    <FollowUp :dialogParam="followUpParam" @close="closeFn"></FollowUp>

    <!-- 导入弹窗 -->
    <el-dialog
      v-model="uploadDia.open"
      :close-on-click-modal="false"
      :title="uploadDia.title"
      append-to-body
      width="400px"
      @close="closeUpload"
    >
      <el-upload
        v-loading="uploadLoading"
        :before-upload="beforeAvatarUpload"
        :http-request="requestFile"
        :show-file-list="false"
        accept=" .xls, .xlsx"
        action="#"
        drag
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div>
            <div class="el-upload__tip text-center">
              <!-- <span class="text-red">仅允许导入蓝字订单</span> -->
              <el-link
                :underline="false"
                style="font-size: 12px; vertical-align: baseline"
                type="primary"
                @click="downUrl"
                >下载模板
              </el-link>
            </div>
            <div v-if="uploadDia.message" style="white-space: pre-line">
              导入结果：{{ uploadDia.message }}
            </div>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitFileForm">确 定</el-button> -->
          <el-button @click="closeUpload">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 转移商机弹窗 -->
    <el-dialog
      v-model="transferDialog.open"
      :close-on-click-modal="false"
      :title="transferDialog.title"
      width="40%"
    >
      <el-form
        ref="formRules"
        :model="transferForm"
        :rules="formStopRules"
        label-width="120px"
        status-icon
      >
        <el-row>
          <el-col :span="24">
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="transferForm.customerName"
                disabled
                placeholder="请输入客户名称"
              />
            </el-form-item>
            <el-form-item label="转移给" prop="userName">
              <el-input
                v-model="transferForm.userName"
                placeholder="请选择人员"
                @focus="selectUserFn('userId')"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="transferDialog.open = false">取 消</el-button>
          <el-button type="primary" @click="handleStopSubmit">保存</el-button>
        </span></template
      >
    </el-dialog>
    <!-- 人员弹出框下拉框 -->
    <SelectDialog
      :dialog-param="dialogParam"
      @close="
        val => {
          dialogParam.isDialog = false
        }
      "
      @ok="selectDialogData"
    />
    <!-- 自定义订单列表弹窗 -->
    <DiaFixTable
      v-model="diaTable.open"
      :dialogParam="diaTable"
      @ok="diaTableFn"
    />
  </div>
</template>

<script name="businessList" setup>
import { reactive, getCurrentInstance, toRefs } from 'vue'
import { useRouter } from 'vue-router'

import {
  business_stage,
  business_source,
  project_type,
  SALESBUSINESSTABLE,
  business_customer_type,
  industry_category,
  popularize_type,
  lost_business_opportunities
} from '@/hooks/dict/business.js'
import {
  getBusinessOpportunityList,
  delBusinessOpportunity,
  transferOpportunity,
  importOpportunityData,
  importFollow
} from '@/api/salesManage/businessManage'
import FollowUp from '@/businessComponents/FollowUp'
import useCommonStore from '@/store/modules/common'
import useUserStore from '@/store/modules/user'
import { addManage } from '@/api/system/notice'
import { parseTime } from '@/utils/ruoyi'
import {
  companyOption, //归属公司
  departmentOption,
  order_status //部门
} from '@/hooks/dict/order'
import { treeselect } from '@/api/rsgl/zzjg'
import { endOfMonth, format, startOfMonth } from 'date-fns'
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
// 通用数据store
const router = useRouter()
const route = useRoute()
const data = reactive({
  loading: false,
  showSearch: true,
  searchFrom: {
    keyword: null, // 名称
    status: null, //商机阶段
    resource: null, //商机来源
    projectType: null, //项目类型
    // pageStyle: [10, 15, 20],
    lastFollowTime: [],
    companyId: useUserStore().userInfo.orgId,
    pageSize: 10,
    pageNum: 1
  },
  total: 0,
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  tableData: [],
  selectionList: [],
  followUpParam: {}, // 跟进弹窗配置
  uploadDiaType: null
})
const {
  loading,
  showSearch,
  searchFrom,
  tableData,
  selectionList,
  followUpParam,
  single,
  multiple,
  total,
  uploadDiaType
} = toRefs(data)
const deptIdOption = ref([])
// 获取部门树
const getDeptTree = () => {
  if (!searchFrom.value.companyId) return
  searchFrom.value.deptId = ''
  let data = { deptId: searchFrom.value.companyId }
  treeselect(data).then(res => {
    deptIdOption.value = res.data
  })
}
getDeptTree()
/** 搜索按钮操作 */
function handleQuery() {
  searchFrom.value.pageNum = 1
  getList()
}
/** 重置按钮操作 */
function resetQuery() {
  searchFrom.value = {
    pageNum: 1,
    pageSize: 10
  }
  getList()
}
//下单
const toOrder = row => {
  console.log('row', row)
  let type = null
  if (row.contactId != row.customerId) {
    type = 'customer'
  } else {
    type = 'cusLink'
  }
  console.log('type', type)
  let obj = {
    customerId: row.customerId,
    customerName: row.customerName,
    customerType: type
  }
  router.push({
    path: '/sales/indent/salesOrderForm',
    query: { salesOrderData: JSON.stringify(obj) }
  })
}
//打开跟进弹窗
function handleContinue(row) {
  /***订单模块 */
  console.log('row==>', row)
  followUpParam.value.isVisible = true
  followUpParam.value.tableName = 'ord_business_opportunity'
  followUpParam.value.businessId = row.id //商机id
  followUpParam.value.customer = row.customerName //客户名称
  followUpParam.value.linkId = row.contactId //'联系人id'
  followUpParam.value.linkName = row.contactName //'联系人名称'
  followUpParam.value.status = row.status //商机状态

  console.log('跟进==》', followUpParam.value)
}
// 组件关闭隐藏
const closeFn = row => {
  // 跟进
  followUpParam.value.isVisible = false
  getList()
}

//添加协作
function addCollaboration() {}
//新建商机
function addItem() {
  router.push({
    path: '/sales/businessManage/addBusiness',
    query: { flag: 'add' }
  })
}
//编辑商机
function editItem() {
  if (!selectionList.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionList.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }

  router.push({
    path: '/sales/businessManage/editBusiness',
    query: { flag: 'update', id: selectionList.value[0].id }
  })
}
//删除
function delItem() {
  if (!selectionList.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal.confirm('是否确认删除选中的客户数据？').then(res => {
    let ids = selectionList.value
      .map(item => {
        return item.id
      })
      .join(',')
    delBusinessOpportunity(ids).then(res => {
      proxy.$modal.msgSuccess('删除成功！')
      getList()
    })
  })
}
//表格选择
function handleSelectionChange(selection) {
  selectionList.value = selection
  console.log('selectionList', selectionList)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
// 客户名称点击
const handleClickProject = row => {
  router.push({
    path: '/sales/businessManage/businessDetails',
    query: { id: row.id }
  })
}
/**
 * 获取商机列表
 */
async function getList() {
  loading.value = true
  let param = { ...searchFrom.value }
  getBusinessOpportunityList(param).then(res => {
    loading.value = false
    tableData.value = res.rows
    total.value = res.total
  })
}

// 导入弹窗
const uploadDia = ref({
  title: '导入商机',
  open: false,
  message: ''
})
// 模板下载
const downUrl = async function downUrl() {
  let url = ''
  if (uploadDiaType.value == 'business') {
    //商机
    url = await commonStore.getUploadTemplateDown(
      'business_opportunity_template'
    )
  } else {
    //跟进
    url = await commonStore.getUploadTemplateDown('fu_commit_import_template')
  }

  // console.info('url', url)
  window.open(url, '_blank')
}
/**导入数据 限制条件
 *
 * @param {*} rawFile
 */
const uploadLoading = ref(false)
function beforeAvatarUpload(rawFile) {
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'))
  const allowType = ['.xls', '.xlsx'].indexOf(ext) > -1
  const isLt2M = rawFile.size / 1024 / 1024 < 200

  if (!allowType) {
    proxy.$message.error('上传文件只能是doc、docx、pdf格式!')
  } else if (!isLt2M) {
    proxy.$message.error('上传文件大小不能超过 200MB!')
  }
  return allowType && isLt2M
}
// 上传文件
async function requestFile(params) {
  uploadLoading.value = true
  let uploadData = new FormData()
  uploadData.append('file', params.file)
  // uploadData.append('type', formData.value.businessType)
  try {
    let res = {}
    if (uploadDiaType.value == 'business') {
      //导入商机模块
      res = await importOpportunityData(uploadData)
    } else {
      //导入跟进模块
      res = await importFollow(uploadData)
    }

    uploadLoading.value = false
    if (res.code === 200) {
      proxy.$modal.msgSuccess('导入成功')
      uploadDia.value.message = '导入成功!'
      getList()
    }
  } catch (error) {
    uploadLoading.value = false
    console.log('error===>', error)
    uploadDia.value.message = error.toString().replace('Error:', '')
  }
}
// 关闭导入弹窗
function closeUpload() {
  uploadDia.value.open = false
  uploadDia.value.message = ''
  uploadDiaType.value = null
}

const dialogParam = ref({})
//导出接口
const exportFn = () => {
  //
  let param = { ...searchFrom.value }
  delete param.pageNum
  delete param.pageSize
  proxy.downLoadByUrl(
    '/ord/business/opportunity/export',
    param,
    '商机列表.xlsx'
  )
}
/**
 * 人员选择
 * @param keyName
 */
function selectUserFn(keyName) {
  switch (keyName) {
    case 'userId':
      dialogParam.value.type = keyName
      dialogParam.value.title = '请选择人员'
      dialogParam.value.isDialog = true
      dialogParam.value.multiple = false
      dialogParam.value.checkStrictly = false
      dialogParam.value.apiParams = {
        disabled: 'true',
        deptId:
          useUserStore().user['orgId'] == '484'
            ? undefined
            : useUserStore().user['orgId']
      }

      dialogParam.value.nodeKey = 'uuid'
      dialogParam.value.defaultCheckedKeys = [transferForm.value[keyName]]
      dialogParam.value.dataType = 'person'
      break
  }
}

// 人员选择确定
const selectDialogData = val => {
  switch (val.type) {
    case 'userId':
      // console.log('val==>', val)
      transferForm.value.userId = val.defaultCheckedKeys[0]
      transferForm.value.userName = val.labelData[0]
      break
  }
}

/* 转移商机开始 */
const transferDialog = ref({
  title: '转移商机',
  open: false
})
const transferForm = ref({
  customerName: [],
  customerId: [],
  userName: '',
  userId: '',
  ids: []
})
const formStopRules = ref({
  userName: [
    {
      required: true,
      message: '请选择人员',
      trigger: ['blur', 'change']
    }
  ]
})

// 清空表单
function resetForm() {
  proxy.resetForm('formRules')
  transferForm.value = {
    customerName: [],
    customerId: [],
    userName: '',
    userId: '',
    ids: []
  }
}
//转移商机
function toBusiness() {
  if (!selectionList.value.length) {
    proxy.$modal.msgWarning('请选择要转移的数据')
    return
  }
  resetForm()
  transferDialog.value.open = true
  transferForm.value.customerName = selectionList.value.map(item => {
    return item.customerName
  })
  transferForm.value.ids = selectionList.value.map(item => {
    return item.id
  })
}

// 保存转移
function handleStopSubmit() {
  proxy.$refs.formRules.validate((valid, msg) => {
    if (valid) {
      let formData = {
        ids: transferForm.value.ids,
        userId: transferForm.value.userId.replace('U', '')
      }
      transferOpportunity(formData).then(res => {
        proxy.$modal.msgSuccess('转移成功')
        transferDialog.value.open = false
        getList()

        let mesVoData = {
          businessId: '商机信息_' + new Date().getTime(), //业务ID
          content: '您接收到新的商机信息', //待办内容
          followDate: undefined, //跟进日期
          followType: undefined, //跟进方式
          impSign: '2', //重要程度:0-非常重要，1-重要，2-一般
          receiver: formData.userId, //接收人
          receiverName: undefined, //接收人中文
          reminderMethod: '0', //提醒方式:0-系统站内，1-邮箱，2-短信，允许多个并存，例如:0,1,2
          sendTime: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'), //发送时间
          sender: useUserStore().user.nickName, //发送人
          serviceType: '16', //业务类型:0-项目，1-订单，2-客户，3-工单，4-任务，5-产品，6-合同，7-公告，8-日程，9-回款, 10-联系人
          title: '您接收到新的商机信息', //待办标题
          type: undefined, //待办类型:0-普通，1-流程
          urgFlag: '2', //紧急程度:0-非常紧急，1-紧急，2-一般
          url: '/sales/businessManage/businessList', //待办链接(多链接用英文逗号隔开)
          urlName: '前往商机' //待办链接名称(多链接名称用英文逗号隔开)
        }
        addManage(mesVoData)
      })
    }
  })
}
/* 转移商机结束 */

/**** 自定义table 列表配置  2024/6/24 gbq */
let tableCol = ref(SALESBUSINESSTABLE)
/* ***
* 参数说明
* open: 打开自定义列表弹窗 true/false
tableName: 列表名称唯一值，用于保存列表配置和获取列表配置
tableCol: 列表列数据
initCol: 初始列表数据用于客户重置为本地的列表数据
*/
// 2. 设置传递的参数变量
const diaTable = ref({
  open: false,
  tableName: 'salesBusinessTable',
  tableCol: tableCol.value,
  initCol: SALESBUSINESSTABLE
})

// 获取列表配置
const diaTableFn = value => {
  tableCol.value = value
}
// 自定义列表
const handleTable = () => {
  diaTable.value = {
    open: true,
    tableName: 'salesBusinessTable', //唯一值防止与其他列表混合
    tableCol: tableCol.value,
    initCol: SALESBUSINESSTABLE
  }
}
// 初始化
async function init() {
  // 初始化列表配置
  if (useUserStore().userInfo.listDisaplayObj?.salesBusinessTable) {
    let _tableCol = JSON.parse(
      useUserStore().userInfo.listDisaplayObj['salesBusinessTable']
    )
    // 过滤出本地新增的列
    let initItmes = SALESBUSINESSTABLE.filter(
      item =>
        !_tableCol.some(item1 => {
          return item1.prop == item.prop
        })
    )
    tableCol.value = []
    _tableCol.forEach(item => {
      let newItem = {}
      for (const e of SALESBUSINESSTABLE) {
        if (e.prop == item.prop) {
          newItem = { ...e, ...item, label: e.label }
          tableCol.value.push(newItem)
          break
        }
      }
    })
    tableCol.value = [...tableCol.value, ...initItmes]
  }
  // 归属部门
  getList()
}
init()
</script>

<style lang="scss" scoped>
.business-page {
  display: block;
  .search-from {
    @apply pb-30px;
  }
  #searchFrom {
    :deep .el-input__wrapper {
      // width: 200px;
      @apply w-200px;
    }
    :deep .el-form-item {
      margin-right: 10px;
    }
  }
}
</style>
